package com.ophiux.system.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.ophiux.common.core.base.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @desc:
 * @author: hhl
 * @date：2023/5/24 9:40
 */

@Api(tags = "Sentinel测试API")
@RequestMapping("/sentinel")
@RestController
public class SentinelTestController {

    public static int coun = 0;


    @GetMapping("/testSlowRequest")
    @ApiOperation("熔断降级测试 -- 慢调用比例")
    @SentinelResource(value = "testSentinelSlowRequest", fallback = "fallback")
    public Result testSlowRequest() {
        try {
            coun = coun + 1;
            Thread.sleep(300);
        } catch (Exception e) {

        }
        return Result.success("成功" + coun);
    }

    @GetMapping("/testExceptionRatio")
    @ApiOperation("熔断降级测试 -- 异常占比")
    @SentinelResource(value = "testSentinelExceptionRatio", fallback = "fallback2")
    public Result testExceptionRatio() {
        coun = coun + 1;
        if (coun % 2 == 0) {
            int i = 1 / 0;
        }
        return Result.success("成功" + coun);
    }

    @GetMapping("/testExceptionCount")
    @ApiOperation("熔断降级测试 -- 异常数")
    @SentinelResource(value = "testSentinelExceptionCount", fallback = "fallback3")
    public Result testExceptionCount() {
        coun = coun + 1;
        if (coun % 3 == 0) {
            int i = 1 / 0;
        }
        return Result.success("成功" + coun);
    }


    @GetMapping("/test")
    @ApiOperation("流量控制测试")
    @SentinelResource(value = "testSentinelFlow", fallback = "fallback4")
    public Result test() {
        coun = coun + 1;
        return Result.success("成功" + coun);
    }

    @GetMapping("/test2")
    @ApiOperation("异常测试")
    public Result test2() {
        coun = coun + 1;
        if (coun % 2 == 0) {
            int i = 1 / 0;
        }
        return Result.success("成功" + coun);
    }

    @GetMapping("/test3")
    @ApiOperation("网关请求微服务超时测试")
    @SneakyThrows
    public Result test3() {
        coun = coun + 1;
        if (coun % 2 == 0) {
            Thread.sleep(4000);
        }
        return Result.success("成功" + coun);
    }

    public Result fallback() {
        return Result.fail("服务降级啦，当前服务器请求过慢，请稍后重试!");
    }

    public Result fallback2() {
        return Result.fail("服务降级啦，当前服务器请求异常占比过多，请稍后重试!");
    }
    public Result fallback3() {
        return Result.fail("服务降级啦，当前服务器请求异常数过多，请稍后重试!");
    }

    public Result fallback4() {
        return Result.fail("服务限流啦，当前服务器请求次数过多，请稍后重试!");
    }
}
